package logic

import (
	"Serve/VideoSrv"
	"Serve/global/model"
	"Serve/internal/svc"
	"context"
	"fmt"

	"github.com/zeromicro/go-zero/core/logx"
)

type AuditLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewAuditLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AuditLogic {
	return &AuditLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *AuditLogic) Audit(in *VideoSrv.AuditRequest) (*VideoSrv.AuditResponse, error) {
	// todo: add your logic here and delete this line
	var video model.Video
	var user model.User
	var audit model.Audit
	user.ID = uint(in.UserId)
	video.ID = uint(in.VideoId)
	if err := model.DB.Where(&user).Find(&user).Error; err != nil {
		return nil, err
	}
	if user.Level == 0 {
		return nil, fmt.Errorf("权限不足")
	}
	if err := model.DB.Where(&video).Find(&video).Error; err != nil {
		return nil, err
	}
	if video.ID == 0 {
		return nil, fmt.Errorf("视频不存在")
	}
	if int(in.AuditStatus) < video.AuditStatus {
		return nil, fmt.Errorf("审核状态不可回退")
	}
	audit = model.Audit{
		VideoId:     int(in.VideoId),
		UserId:      int(in.UserId),
		AuditStatus: int(in.AuditStatus),
	}
	audits := model.DB.Begin()
	if err := audits.Create(&audit).Error; err != nil {
		audits.Rollback()
		return nil, err
	}
	if err := audits.Model(&model.Video{}).Where("id = ?", in.VideoId).Updates(model.Video{AuditStatus: int(in.AuditStatus)}).Error; err != nil {
		audits.Rollback()
		return nil, err
	}
	return &VideoSrv.AuditResponse{}, nil
}
